const {ipcMain} = require('electron');
const robot = require('robotjs');
const vkey = require('vkey');

const {log} = require('../../../utils/log');

const mapButton = (_button) => {
  let button;
  switch (_button) {
    case 0:
      button = 'left';
      break;
    case 1:
      button = 'middle'
      break;
    case 2:
      button = 'right'
      break;
  }

  return button;
};

// data {clientX, clientY, screen:{width,height}, video:{width,height}, button}
const mapMousePosition = ({pageX, pageY, screen, video}) => {
  return {
    x: pageX * screen.width / video.width,
    y: pageY * screen.height / video.height
  }
};

function handleMouseDown({button:_button}) {
  const button = mapButton(_button);
  log('robot handleMouseDown--- --- ---button:',button);

  if(button === 'left'){
    robot.mouseToggle("down");
  }
}


function handleMouseUp({button:_button}){
  const button = mapButton(_button);
  log('robot handleMouseUp--- --- ---button:',button);

  // robot.moveMouse(x, y);

  if(button === 'left'){
    robot.mouseToggle("up",'left'/*默认就是left*/);
  }else {
    robot.mouseClick(button/*todo ,double?:boolean, 貌似没撒必要, 快速点两次就是双击, 并且我们这里鼠标点击事件没有节流, 响应是很块的*/);
  }
}

function handleMouseMove(data){
  // log('robot handleMouseMove--- --- ---');
  const {x, y} = mapMousePosition(data);
  robot.moveMouse(x, y);
}

//data {keyCode, meta, alt, control, shift}
function handleKey(data){
  log('robot handleKey--- --- ---');
  const modifiers = [];
  if(data.meta) modifiers.push('command'/*win/command, robotjs里统一为command*/);
  if(data.shift) modifiers.push('shift');
  if(data.alt) modifiers.push('alt');
  if(data.control) modifiers.push('control');

  log('handleKey keyCode:',data.keyCode);
  let key = vkey[data.keyCode].toLowerCase();
  log('handleKey key:',key); // 1 2 3 a b c ...
  //如果是shift enter alt command/win space(即空格) control 会带上 `<>` 进行包裹
  //<shift> 、 <enter> ...
  if(key[0]==='<'){
    key = key.substring(1, key.length - 1);
    if (key === 'meta') key = 'command'; //robotjs里windows的win和mac的command统一叫command
  }

  robot.keyTap(key, modifiers);
}


module.exports = function(){
  ipcMain.on('robot',(e,type,data)=>{
    switch (type){
      case 'mousedown':
        handleMouseDown(data)
        break;
      case 'mouseup':
        handleMouseUp(data)
        break;
      case 'mousemove':
        handleMouseMove(data)
        break;
      case 'key':
        handleKey(data);
        break;
      default:
    }
  })
}

//todo
// 1. 这里有个奇怪的bug, 试图拖拽被控制方的主程序窗口（yueerlan）时会卡主, 不再响应任何指令 (但只要在被控制方手动点击一下左键,就又恢复如常了(点击的时候你会发现鼠标乱跑了一下))
// 2. 关闭被控制方的一个窗口 或则 双击打开某个文件时 也可能出现上面卡主的情况
